package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.PublishConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.PStoreCart;
import com.ruoyi.system.domain.PStoreProduct;
import com.ruoyi.system.domain.PStoreProductAttrValue;
import com.ruoyi.system.domain.bo.PStoreCartBo;
import com.ruoyi.system.domain.vo.CartInfoResponse;
import com.ruoyi.system.domain.vo.PStoreCartVo;
import com.ruoyi.system.domain.vo.PStoreProductVo;
import com.ruoyi.system.mapper.PStoreCartMapper;
import com.ruoyi.system.mapper.PStoreProductAttrValueMapper;
import com.ruoyi.system.mapper.PStoreProductMapper;
import com.ruoyi.system.service.IPStoreCartService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 购物车Service业务层处理
 *
 * @author ruoyi
 * @date 2022-08-01
 */
@RequiredArgsConstructor
@Service
public class PStoreCartServiceImpl implements IPStoreCartService {

    private final PStoreCartMapper baseMapper;
    private final PStoreProductMapper productMapper;
    private final PStoreProductAttrValueMapper attrValueMapper;

    /**
     * 查询购物车
     */
    @Override
    public PStoreCartVo queryById(Integer id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询购物车列表
     */
    @Override
    public TableDataInfo<PStoreCartVo> queryPageList(PStoreCartBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PStoreCart> lqw = buildQueryWrapper(bo);
        Page<PStoreCartVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询购物车列表
     */
    @Override
    public List<PStoreCartVo> queryList(PStoreCartBo bo) {
        LambdaQueryWrapper<PStoreCart> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PStoreCart> buildQueryWrapper(PStoreCartBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PStoreCart> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUid() != null, PStoreCart::getUid, bo.getUid());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), PStoreCart::getType, bo.getType());
        lqw.eq(bo.getProductId() != null, PStoreCart::getProductId, bo.getProductId());
        lqw.eq(StringUtils.isNotBlank(bo.getProductAttrUnique()), PStoreCart::getProductAttrUnique, bo.getProductAttrUnique());
        lqw.eq(bo.getCartNum() != null, PStoreCart::getCartNum, bo.getCartNum());
        lqw.eq(bo.getIsNew() != null, PStoreCart::getIsNew, bo.getIsNew());
        lqw.eq(bo.getCombinationId() != null, PStoreCart::getCombinationId, bo.getCombinationId());
        lqw.eq(bo.getSeckillId() != null, PStoreCart::getSeckillId, bo.getSeckillId());
        lqw.eq(bo.getBargainId() != null, PStoreCart::getBargainId, bo.getBargainId());
        lqw.eq(bo.getStatus() != null, PStoreCart::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增购物车
     */
    @Override
    public String insertByBo(PStoreCartBo bo) {
        // 检验商品
        Long productId = bo.getProductId();
        PStoreProductVo product = productMapper.selectVoById(productId);
        if (ObjectUtil.isEmpty(product) || "0".equals(product.getIsShow())) {
            throw new ServiceException("未找到该商品！");
        }

        String productAttrUnique = bo.getProductAttrUnique();
        List<PStoreProductAttrValue> attrValues = attrValueMapper.selectList(
            new LambdaQueryWrapper<PStoreProductAttrValue>()
                .eq(PStoreProductAttrValue::getId, productAttrUnique)
                .eq(PStoreProductAttrValue::getProductId, productId)
                .eq(PStoreProductAttrValue::getType, "0")
        );

        if (CollUtil.isEmpty(attrValues)) {
            throw new ServiceException("未找到对应的商品SKU");
        }

        Long userId = LoginHelper.getUserId();
        List<PStoreCart> carts = baseMapper.selectList(new LambdaQueryWrapper<PStoreCart>().eq(PStoreCart::getProductAttrUnique, productAttrUnique)
            .eq(PStoreCart::getUid, userId));
        if (CollectionUtil.isNotEmpty(carts)) {
            PStoreCart storeCart = carts.get(0);
            storeCart.setCartNum(storeCart.getCartNum() + bo.getCartNum());
            baseMapper.updateById(storeCart);
            return storeCart.getId() + "";
        } else {
            PStoreCart add = BeanUtil.toBean(bo, PStoreCart.class);
            add.setUid(userId);
            add.setType("product");
            baseMapper.insert(add);
            return add.getId() + "";
        }
    }

    /**
     * 修改购物车
     */
    @Override
    public Boolean updateByBo(PStoreCartBo bo) {
        PStoreCart update = BeanUtil.toBean(bo, PStoreCart.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PStoreCart entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除购物车
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public long getCount() {
        Long userId = LoginHelper.getUserId();
        return baseMapper.selectCount(new LambdaQueryWrapper<PStoreCart>()
            .eq(PStoreCart::getUid, userId)
            .eq(PStoreCart::getIsNew, PublishConstants.COMMON_NO)
        );
    }

    @Override
    public TableDataInfo<CartInfoResponse> queryPageFontList(PStoreCartBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        bo.setUid(userId);
        bo.setIsNew(PublishConstants.COMMON_NO);
        LambdaQueryWrapper<PStoreCart> lqw = buildQueryWrapper(bo);
        Page<CartInfoResponse> result = baseMapper.selectResponsePage(pageQuery.build(), lqw);
        if (ObjectUtil.isNotEmpty(result)) {
            List<CartInfoResponse> responses = result.getRecords();
            if (CollUtil.isNotEmpty(responses)) {
                for (CartInfoResponse store : responses) {
                    // 填充商品信息
                    Integer productId = store.getProductId();
                    PStoreProduct product = productMapper.selectByLeftId(productId);
                    store.setImage(product.getFileName());
                    store.setStoreName(product.getStoreName());
                    // 填充对应的商品规则信息
                    List<PStoreProductAttrValue> attrValueList = attrValueMapper.selectList(
                        new LambdaQueryWrapper<PStoreProductAttrValue>()
                            .eq(PStoreProductAttrValue::getId, store.getProductAttrUnique())
                            .eq(PStoreProductAttrValue::getProductId, productId)
                            .eq(PStoreProductAttrValue::getType, "0")
                    );
                    // 规格不存在即失效
                    if (CollUtil.isEmpty(attrValueList)) {
                        store.setAttrStatus(false);
                        continue ;
                    }

                    PStoreProductAttrValue attrValue = attrValueList.get(0);
//                    if (StrUtil.isNotBlank(attrValue.getImage())) {
//                        store.setImage(attrValue.getImage());
//                    }
                    store.setAttrId(attrValue.getId());
                    store.setSuk(attrValue.getSku());
                    store.setPrice(attrValue.getPrice());
                    store.setAttrStatus(attrValue.getStock() > 0);
                    store.setStock(attrValue.getStock());
                }
            }

        }

        return TableDataInfo.build(result);
    }

    @Override
    public void updateByFontBo(long id, int number) {
        if (ObjectUtil.isEmpty(id) || ObjectUtil.isEmpty(number)) {
            throw new ServiceException("非法参数！");
        }

        if (number <= 0 || number > 99) {
            throw new ServiceException("商品数量不能小于1大于99！");
        }

        PStoreCart cart = baseMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(cart)) {
            cart.setCartNum(number);
            baseMapper.updateById(cart);
        }

    }

    @Override
    public void resetCart(PStoreCartBo bo) {
        Long id = bo.getId();
        if (ObjectUtil.isEmpty(id)) {
            throw new ServiceException("必要参数不能为空!");
        }

        PStoreCart cart = baseMapper.selectById(bo.getId());
        if (ObjectUtil.isEmpty(cart)) {
            throw new ServiceException("非法购物车！");
        }

        Integer cartNum = bo.getCartNum();
        if (ObjectUtil.isNull(cartNum) || cartNum <= 0 || cartNum >= 999)
            throw new ServiceException("数量不合法");
        cart.setCartNum(cartNum);
        cart.setProductAttrUnique(bo.getProductAttrUnique() + "");

        baseMapper.updateById(cart);
    }

    @Override
    public TableDataInfo<PStoreCart> cartList(PageQuery pageQuery) {
        pageQuery.setPageNum((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
        List<PStoreCart> list = this.baseMapper.selectByCustom(pageQuery, LoginHelper.getUserId());
        return TableDataInfo.build(list);
    }

    @Override
    public String insertFontByBo(PStoreCartBo bo) {
        // 检验商品
        Long productId = bo.getProductId();
        PStoreProductVo product = productMapper.selectVoById(productId);
        if (ObjectUtil.isEmpty(product) || "0".equals(product.getIsShow())) {
            throw new ServiceException("未找到该商品！");
        }

        Long userId = LoginHelper.getUserId();
        // 校验购物车是否存在该商品
        List<PStoreCart> carts = baseMapper.selectList(new LambdaQueryWrapper<PStoreCart>().eq(PStoreCart::getProductId, productId).eq(PStoreCart::getUid, userId));
        if (CollectionUtil.isNotEmpty(carts)) {
            PStoreCart storeCart = carts.get(0);
            storeCart.setCartNum(storeCart.getCartNum() + bo.getCartNum());
            baseMapper.updateById(storeCart);
            return storeCart.getId() + "";
        } else {
            PStoreCart add = BeanUtil.toBean(bo, PStoreCart.class);
            add.setUid(userId);
            baseMapper.insert(add);
            return add.getId() + "";
        }
    }

}
